// 引入操作数据库的方法
const db = require('../db/index')
var path = require("path");
var _ = require('lodash');
const { array } = require('joi');
const { add, split } = require('lodash');
// 获取树状结果
function getTreeResult(keyCategories, Categories, type) {
    var result = [];
    for (idx in Categories) {
        var cat = Categories[idx]
        if (cat.cat_level == 0) {
            // 一级分类列表
            result.push(cat);
        } else {
            if (cat.cat_level >= type) continue;
            var parentCat = keyCategories[cat.cat_pid]
            if (!parentCat) continue;
            if (!parentCat.children) {
                parentCat['children'] = []
            }
            parentCat.children.push(cat)
        }
    }
    return result
}

// 商品分类数据列表
exports.getCategories = (req, res) => {
    // res.ResData('商品参数分类')
    // console.log(req.query.type, req.query.pagenum, req.query.pagesize);
    // console.log(req.query);
    var type = req.query.type;
    var pagenum = req.query.pagenum //当前页码值
    var pagesize = req.query.pagesize
    var sql = 'select *from sp_category'
    db.query(sql, (err, result) => {
        if (err) return res.ResData(err)
            // console.log(result)
        var keyCategories = _.keyBy(result, 'cat_id')
            // console.log(keyCategories);
        if (!type) type = 3;
        var resultdata = getTreeResult(keyCategories, result, type)
            // res.ResData(resultdata)
        if (pagenum && pagesize) {
            count = resultdata.length //总条数 
            pagenum = parseInt(pagenum)
            pagesize = parseInt(pagesize)
            data = _.take(_.drop(resultdata, (pagenum - 1) * pagesize), pagesize)
                // console.log(data);
            data = {
                "total": count,
                "pagenum": pagenum,
                "pagesize": pagesize,
                data
            }
            return res.ResData("获取参数列表", 200, data)
        }
        res.ResData("获取参数列表", 200, resultdata)
    })
}

// 添加分类
exports.addCategories = (req, res) => {
    // res.ResData('添加分类')
    var pid = req.body.cat_pid
    var name = req.body.cat_name
    var level = req.body.cat_level
        // console.log(id, name, level);
        // 检查角色是否存在
    var sql = 'select * from sp_category where cat_name=?'
    db.query(sql, [name], (err, result) => {
        if (err) res.ResData(err)
        if (result.length > 0) {
            return res.ResData('用户名已经存在')
        }


        var sql1 = 'insert into sp_category (cat_name,cat_pid,cat_level) values(?,?,?)'
        db.query(sql1, [name, pid, level], (err, data) => {
            if (err) return res.ResData(err)
            res.ResData('创建成功', 201, {
                // "cat_id": ,
                "cat_name": name,
                "cat_pid": pid,
                "cat_level": level
            })
        })
    })
}

// 根据id查询分类
exports.searchCategories = (req, res) => {
    // res.ResData('根据id查询分类');
    var id = req.params.id
        // console.log(id);
    var sql = 'select * from sp_category where cat_id=?'
    db.query(sql, [id], (err, result) => {
        if (err) return res.ResData(err)
        if (result.length > 0) {
            res.ResData('获取成功', 200, {
                "cat_id": result[0].cat_id,
                "cat_name": result[0].cat_name,
                "cat_pid": result[0].cat_pid,
                "cat_level": result[0].cat_level
            })
        }
    })
}

// 编辑提交分类
exports.EditCategories = (req, res) => {
    // res.ResData('编辑提交分类')
    var id = req.params.id
        // console.log(id);
    var name = req.body.name
        // console.log(name);
    var sql = 'update sp_category set cat_name=? where cat_id=?'
    db.query(sql, [name, id], (err, result) => {
        if (err) return res.ResData(err)
        if (result.length < 1) return res.ResData('分类名称已经存在')
        var sql1 = 'select * from sp_category where cat_name=?'
        db.query(sql1, [id], (err, result) => {
            // console.log(result);
            if (err) return res.ResData(err)
            res.ResData('更新成功', 200, {
                "cat_id": result[0].cat_id,
                "cat_name": result[0].cat_name,
                "cat_pid": result[0].cat_pid,
                "cat_level": result[0].cat_level
            })
        })

    })

}

//删除分类
exports.addsearchCategories = (req, res) => {
    res.send('删除角色')
    var id = req.params.id
    console.log(id);
    // var sql = "delete from sp_role where role_id=?"
    // db.query(sql, [id], (err, result) => {
    // if (err) return res.ResData(err)
    // if (result.affectedRows != 1) return res.ResData("删除失败")
    // res.ResData("删除成功", 200)
    // })

}

//获取参数列表
exports.selectCategories = (req, res) => {
    sel = req.query.sel;
    // console.log(req.query);
    // console.log(res.params.sel);
    var id = req.params.id
    var data = []
    var sql = "SELECT * FROM sp_attribute WHERE  cat_id=?  AND attr_sel = ? AND delete_time is NULL"
    db.query(sql, [id, sel], (err, result) => {
        // console.log(result);
        if (err) return res.ResData(err)
        if (result.length > 0) {
            for (let i = 0; i < result.length; i++) {
                data.push({
                    "attr_id": result[i].attr_id,
                    "attr_name": result[i].attr_name,
                    "cat_id": result[i].cat_id,
                    "attr_sel": result[i].attr_sel,
                    "attr_write": result[i].attr_write,
                    "attr_vals": result[i].attr_vals
                })
            }
            res.ResData('获取成功', 200, {
                data
            })

        }
    })
}

//根据 ID 查询参数
exports.selectIdCategories = (req, res) => {
    var id = req.params.id
    var ids = req.params.attrId
    var sel = req.query.attr_sel
        // console.log(id);
        // console.log(ids);
        // console.log(sel);
    var sql = "SELECT * FROM sp_attribute WHERE cat_id=? AND attr_id=? AND attr_sel=?"
    db.query(sql, [id, ids, sel], (err, result) => {
        var data = []
            // console.log(result);
        if (err) return res.ResData(err)
        if (result.length > 0) {
            // console.log(result);
            res.ResData('获取成功', 200, {
                "attr_id": result[0].attr_id,
                "attr_name": result[0].attr_name,
                "cat_id": result[0].cat_id,
                "attr_sel": result[0].attr_sel,
                "attr_write": result[0].attr_write,
                "attr_vals": result[0].delete_time
            })
        }
    })
}

//添加动态参数或者静态属性
exports.UpdataCategories = (req, res) => {
    var cat_ids = req.params.id
    var attr_name = req.body.attr_name
    var attr_sel = req.body.attr_sel
        // console.log(cat_ids);
        // console.log(attr_name);
        // console.log(attr_sel);
    if (!cat_ids) {
        return res.ResData(null, 400, "分类ID不能为空");
    }
    if (isNaN(parseInt(cat_ids))) return res.ResData(null, 400, "分类ID必须是数字");

    if (!attr_name) return res.ResData(null, 400, "参数名称不能为空");

    if (!attr_sel || (attr_sel != "only" && attr_sel != "many")) {
        return res.ResData(null, 400, "参数 attr_sel 类型必须为 only 或 many");
    }
    if (attr_sel == "only") {
        attr_write = 'manual'
    } else {
        attr_write = 'list'
    }
    // console.log(req.body.attr_vals);
    var sql = "INSERT INTO `sp_attribute` VALUES (DEFAULT, ?, ?, ?, ?, ?, NULL);"

    db.query(sql, [attr_name, cat_ids, attr_sel, attr_write, ''], (err, result) => {
        if (err) return res.ResData(err)
        var sql1 = "SELECT * FROM sp_attribute WHERE cat_id=? and attr_sel=? "
        db.query(sql1, [cat_ids, attr_sel], (err, resuly) => {
            // console.log(resuly);
            var retUsers = []
            for (let i = 0; i < resuly.length; i++) {
                retUsers.push({
                    "attr_id": resuly[i].attr_id,
                    "attr_name": resuly[i].attr_name,
                    "cat_id": resuly[i].cat_id,
                    "attr_sel": resuly[i].attr_sel,
                    "attr_write": resuly[i].attr_write,
                    "attr_vals": resuly[i].attr_vals
                })
            }
            // console.log(retUsers);
            res.ResData('创建成功', 201, retUsers)
        })

    })
}

//编辑提交参数
exports.tijiaoIdCategories = (req, res) => {
        var id = req.params.id
        var ids = req.params.attrId
        var name = req.body.attr_name
            // console.log(id);
            // console.log(ids);
            // console.log(name);
            // res.ResData(name)
        var sql = "UPDATE sp_attribute SET attr_name=?  WHERE cat_id=? AND attr_id=?"
        db.query(sql, [name, id, ids], (err, result) => {
            if (err) return res.ResData(err)
            sql1 = "SELECT*FROM sp_attribute WHERE cat_id=? AND attr_id=?"
            db.query(sql1, [id, ids], (err, result) => {
                // console.log(result);
                if (err) return res.ResData(err)
                res.ResData("更新成功", 200, {
                    "attr_id": result[0].attr_id,
                    "attr_name": result[0].attr_name,
                    "cat_id": result[0].cat_id,
                    "attr_sel": result[0].attr_sel,
                    "attr_write": result[0].attr_write,
                    "attr_vals": result[0].attr_vals
                })
            })

        })
    }
    //删除参数
exports.deleteIdCategories = (req, res) => {
        var id = req.params.id
        var ids = req.params.attrid
            // console.log(id);
            // console.log(ids);
        sql = 'DELETE  FROM sp_attribute WHERE cat_id=? AND attr_id=?'
        db.query(sql, [id, ids], (err, status) => {
            if (err) return res.ResData(err)
            res.ResData('删除成功', 200, null)
        })
    }
    //编辑提交参数
exports.tijiaoIdCategories = (req, res) => {
    id = req.params.id
    ids = req.params.attrId
        // console.log(req.params, req.body);
        // console.log(req.body);
    sql = 'SELECT*FROM sp_attribute WHERE cat_id=? AND attr_id=?'
    db.query(sql, [id, ids], (err, status) => {

        // console.log(str);
        // console.log(str1);

        if (err) return res.ResData(err)
        if (!req.body.attr_vals) {
            return res.ResData('属性不能为空')
        } else {
            str = req.body.attr_vals
            str1 = status[0].attr_vals
            if (str !== str1) {
                sqld = "UPDATE sp_attribute SET attr_vals=? WHERE cat_id=? AND attr_id=?"
                db.query(sqld, [str, id, ids], (err, rea) => {
                    if (err) return res.ResData(err)
                })
                res.ResData('更新成功', 200, {
                    "attr_id": status[0].attr_id,
                    "attr_name": status[0].attr_name,
                    "cat_id": status[0].cat_id,
                    "attr_sel": status[0].attr_sel,
                    "attr_write": status[0].attr_write,
                    "attr_vals": status[0].attr_vals
                })
            } else {
                addc = req.body.attr_vals.split(' ')
                vals = status[0].attr_vals + ' ' + addc[addc.length - 1]
                    // console.log(vals);
                sql1 = "UPDATE sp_attribute SET attr_vals=? WHERE cat_id=? AND attr_id=?"
                db.query(sql1, [vals, id, ids], (err, rea) => {
                    if (err) return res.ResData(err)
                })
                res.ResData('更新成功', 200, {
                    "attr_id": status[0].attr_id,
                    "attr_name": status[0].attr_name,
                    "cat_id": status[0].cat_id,
                    "attr_sel": status[0].attr_sel,
                    "attr_write": status[0].attr_write,
                    "attr_vals": status[0].attr_vals
                })
            }
        }
    })
}